/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package client.views;

import client.beans.AuthBean;
import client.beans.ServerBean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.FacesException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.xml.bind.JAXBException;
import types.AuthXML;
import types.ErrorXML;
import types.ResponseXML;

/**
 *
 * @author efim
 */
@ManagedBean
@RequestScoped
public class LoginView {
    @EJB
    private AuthBean authBean;
    @EJB
    private ServerBean serverBean;  
    

    /**
     * Creates a new instance of LoginView
     */
    public LoginView() {
        
    }
    
    private String email;

    /**
     * Get the value of email
     *
     * @return the value of email
     */
    public String getEmail() {
        return email;
    }

    /**
     * Set the value of email
     *
     * @param email new value of email
     */
    public void setEmail(String email) {
        this.email = email;
    }

    private String password;

    /**
     * Get the value of password
     *
     * @return the value of password
     */
    public String getPassword() {
        return password;
    }

    /**
     * Set the value of password
     *
     * @param password new value of password
     */
    public void setPassword(String password) {
        this.password = password;
    }

       
    public String postLogin()
    {        
        try {
            
            ResponseXML<Object> data = (ResponseXML<Object>)serverBean.queryAccessToken(email, password);
            Object item = data.getData().getItems().get(0);
            if(item instanceof AuthXML)
            {
                AuthXML auth = (AuthXML)item;
                authBean.setAccessToken(auth.getAccessToken());
                authBean.setUserId(auth.getUserId());                
            }else
            {
              ErrorXML error = (ErrorXML)item;
              throw new FacesException(error.getReason());   
            }            
            return "panel";
        } catch (JAXBException ex) {
            Logger.getLogger(LoginView.class.getName()).log(Level.SEVERE, null, ex);
        } 
        return "index"; 
    }
}
